﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using MetroCashLib;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Globalization.DateTimeFormatting;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace MetroCash
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class PProfileBrowse : MetroCash.Common.LayoutAwarePage
    {
        private string profileName;
        private ResourceLoader resLoader;
        private ObservableCollection<Profile> avaiProfiles;
        public PProfileBrowse()
        {
            this.InitializeComponent();
            this.resLoader = new ResourceLoader();
            Loaded += PProfileBrowse_Loaded;
        }

        async void PProfileBrowse_Loaded(object sender, RoutedEventArgs e)
        {
            var profileFolder = await Windows.Storage.ApplicationData.Current.RoamingFolder.GetFolderAsync(SettingStrings.PROFILE_FOLDER_NAME);
            var files = await profileFolder.GetFilesAsync();
            this.avaiProfiles = new ObservableCollection<Profile>();
            foreach (StorageFile file in files)
            {
                this.avaiProfiles.Add(new Profile { Name = file.Name, Created = file.DateCreated });
            }
            this.lstProfiles.DataContext = this.avaiProfiles;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {

        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void lstProfiles_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            string profileName = (e.ClickedItem as Profile).Name;
            Windows.Storage.ApplicationData.Current.RoamingSettings.Values[SettingStrings.ROAMING_CURRENT_PROFILE] = profileName;

            if (this.Frame != null)
            {
                this.Frame.Navigate(typeof(PProfileAccounts), profileName);
            }
        }

        private void lstProfiles_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (this.lstProfiles.SelectedItems.Count > 0)
            {
                this.appbarBottom.IsSticky = true;
                this.appbarBottom.IsOpen = true;
            }
            else
            {
                this.appbarBottom.IsSticky = false;
                this.appbarBottom.IsOpen = false;
            }
        }

        private void btnAppBarAdd_Click_1(object sender, RoutedEventArgs e)
        {
            if (this.Frame != null)
            {
                this.Frame.Navigate(typeof(PCreateProfile));
            }
        }

        private async  void btnAppBarDelete_Click_1(object sender, RoutedEventArgs e)
        {
            bool delete = false;
            var contMsg = new MessageDialog("Do you want to delete these profiles? You will NOT able to get them back in the future.", "Warning: deletion confirmation!");
            contMsg.Commands.Add(new UICommand("Continue", (UICommandInvokedHandler) =>
            {
                delete = true;
            }));
            contMsg.Commands.Add(new UICommand("No, keep them safe!"));
            contMsg.DefaultCommandIndex = 1;
            await contMsg.ShowAsync();
            if (delete)
            {
                var deleteFiles = (this.lstProfiles.SelectedItems);
                var profileFolder = await Windows.Storage.ApplicationData.Current.RoamingFolder.GetFolderAsync(SettingStrings.PROFILE_FOLDER_NAME);

                for (int i = deleteFiles.Count; i > 0; i--)
                {
                    var files = await profileFolder.GetFileAsync((deleteFiles[i-1] as Profile).Name);
                    await files.DeleteAsync();
                    (this.lstProfiles.DataContext as ObservableCollection<Profile>).Remove(deleteFiles[i-1] as Profile);
                }
            }
        }

        private void appbarBottom_Opened_1(object sender, object e)
        {
            if (this.lstProfiles.SelectedItems.Count == 0)
            {
                this.btnAppBarDelete.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            else
            {
                this.btnAppBarDelete.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
        }
    }

    class Profile
    {
        public string Name { get; set; }
        public DateTimeOffset Created { get; set; }
        public DateTimeOffset Modified { get; set; }
    }

    public class DateTimeToStringConverter : IValueConverter
    {
        #region IValueConverter Members

        private ResourceLoader resLoader;
        
        // Define the Convert method to change a DateTime object to 
        // a month string.
        public object Convert(object value, Type targetType,
            object parameter, string language)
        {
            this.resLoader = new ResourceLoader();
            // The value parameter is the data from the source object.
            DateTimeOffset thisdate = (DateTimeOffset)value;
            string result = Windows.Globalization.DateTimeFormatting.DateTimeFormatter.ShortDate.Format(thisdate) + " " + Windows.Globalization.DateTimeFormatting.DateTimeFormatter.ShortTime.Format(thisdate);

            // Return the month value to pass to the target.
            return String.Format(this.resLoader.GetString("Common-Created-Str"), result);
        }

        // ConvertBack is not implemented for a OneWay binding.
        public object ConvertBack(object value, Type targetType,
            object parameter, string language)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
